import random
from asyncio.log import logger
from random import randint

from django.shortcuts import render
from rest_framework.views import APIView
from django_redis import get_redis_connection
from rest_framework.response import Response

# Create your views here.
from uaclient import status
from xdg.Exceptions import ValidationError
from . import constants
from meiduo.libs.sms import send_sms_single

class SMSCodeView(APIView):
    '''
    短信验证码
    '''
    def get(self,request,mobile):

        # 1.生成验证码
        sms_code = '%06d' % randint(0,999999)
        logger.info(sms_code)
        # 2.创建redis连接对象
        redis_conn = get_redis_connection('verify_codes')

        # 判断⽤户是否是在60s内发送短信
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return Response({'message': '频繁发送短信'}, status=status.HTTP_400_BAD_REQUEST)

        # 3.把验证码存储到redis数据库
        # 保存短信验证码
        redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 保存发送短信验证码的标记
        redis_conn.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # 4.利用发送短信验证码
        # 发送短信
        template_id = constants.TENCENT_SMS_TEMPLATE['register']
        sms = send_sms_single(mobile, template_id, [sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60])#  constants.SMS_CODE_REDIS_EXPIRES // 60:指的是几分钟内填写验证码
        if sms['result'] != 0:
            raise ValidationError("短信发送失败，{}".format(sms['errmsg']))

        # 5.响应
        return Response({'message':'ok'})


